package 并发;

import java.util.HashSet;
import java.util.Set;

public class VolatileTest {

    public volatile static int flag = 0;
    static int x = 0, y = 0;
    static int a = 0, b = 0;

    public static void main(String[] args) throws InterruptedException {
        Set<String> resultSet = new HashSet<>();

        for (int i = 0; i < 1000000; i++) { // 100万

            x = 0; y = 0;
            a = 0; b = 0;

            Thread t1 = new Thread(() -> {
                a = y;  // 1
                x = 1;  // 2
            });

            Thread t2 = new Thread(() -> {
                b = x;  // 3
                y = 1;  // 4
            });

            t1.start();
            t2.start();

            t1.join();
            t2.join();

            resultSet.add(String.format("a=%d,b=%d", a, b));
        }

        System.out.println(resultSet);
    }

    /*public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                while (true){
                    if(flag == 1){
                        System.out.println("A 终止");
                        break;
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("B 通知 A 完成");
                flag = 1;
            }
        }).start();
    }*/
}
